﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Data.SqlClient;
using BaseObject.Logic.BackMangage;
using DevExpress.Xpo;
using BaseClassUse.PObject.MPManage;

namespace JFLERP.IQ
{
    public partial class frmSOAnalyzeForSAP : DevExpress.XtraEditors.XtraForm, IMdiChildActions
    {


        public frmSOAnalyzeForSAP()
        {
            InitializeComponent();


        }

        #region IMdiChildActions 成员

        public void Save()
        {

        }

        public void New()
        {

        }

        public void Delete()
        {

        }

        public void Print()
        {

        }

        public void SelectAll()
        {

        }

        public void Find()
        {

        }

        public void Export()
        {

        }

        #endregion



        private void GetDataFromSystem()
        {

            try
            {

                this.gridView1.Columns.Clear();

                
                StringBuilder sbSql = new StringBuilder();
                sbSql.AppendFormat(" exec  sp_GetSAP_SOITEM_Analysis_Report @LotNumber='{0}'", txtLotNumber.Text);
                System.Data.DataTable dt = DbHelperSQL.Query(sbSql.ToString()).Tables[0];
                this.gridControl1.DataSource = dt;
                CFunctionUtility.InitGridViewFormatStyle(this.gridView1, "EvsF", "E->F", Color.Yellow, false);
                CFunctionUtility.InitGridViewFormatStyle(this.gridView1, "EvsF", "F->E", Color.Purple, false);
                CFunctionUtility.InitGridViewFormatStyle(this.gridView1, "Tracking_Status", "N", Color.Yellow, false);
                CFunctionUtility.InitGridViewFormatStyle(this.gridView1, "MAT_Status", "ZE", Color.Red, false);
                //
                if (dt.Rows.Count > 0)
                {
                    //txtFileName.Text = dt.Rows[0]["BIName"].ToString() + ".xlsx";
                }
                this.gridView1.BestFitColumns();
                this.Text = "销售订单分析平台[" + dt.Rows.Count.ToString() + "]条记录.";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.GetDataFromSystem();

        }

    
        private void gdv_MpsMain_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gdv_MpsMain);
        }

        private void gdv_MpsMain_KeyDown(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyDown(e, out boolCopy);
        }
        bool boolCopy = false;
        private void gdv_MpsMain_KeyUp(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyUp(e, this.gdv_MpsMain, out boolCopy);
        }

        private void frmStatusMonitor_JobMatReq_Load(object sender, EventArgs e)
        {
            CFunctionUtility.InitGridViewSetColumnReadOnly(this.gridView1, false);

            if (CFunctionUtility.IsSysAdmin())
            {
                txtUpload_GY.Enabled = true;
            }

            txtUserName.Text = Commoner.UseName.Trim();
  
            ///不是管理员不显示
            if (!CFunctionUtility.IsSysAdmin())
            {
                this.txtUserName.Visible = false;
            }
            else
            {
                this.txtUserName.Visible = true;
            }
        }
  
        List<SAP_SOITEM_Analysis> LstSAPUploadList = new List<SAP_SOITEM_Analysis>();
       
        private void gdv_MpsMain_CustomDrawRowIndicator_1(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gdv_MpsMain);
        }

        private void gdv_MpsMain_KeyDown_1(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyDown(e, out boolCopy);
        }

        private void gdv_MpsMain_KeyUp_1(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyUp(e, this.gdv_MpsMain, out boolCopy);
        }

        private void gdv_MpsMain_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            DataRow dr = gdv_MpsMain.GetDataRow(e.RowHandle);
       
        }

        private void chkIsShowOperator_CheckedChanged(object sender, EventArgs e)
        {

            foreach (DevExpress.XtraGrid.Columns.GridColumn item in gdv_MpsMain.Columns)
            {

            }

        }

        private void txtItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtLotNumber.Text))
            {
                txtLotNumber.Text = DateTime.Now.ToString("yyyyMMddHHmmss");
            }
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
       
            txtPath.Text = opf.FileName;

            DOUploadMaterialOrderList();

        }


        private void DOUploadMaterialOrderList()
        {
            StringBuilder sb_WorkOrder = new StringBuilder();
            LstSAPUploadList.Clear();
            try
            {

                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 0; i < dt_excel.Rows.Count; i++)
                    {
                        string _Order = dt_excel.Rows[i][0].ToString();
                        string _Item = dt_excel.Rows[i][1].ToString();
                        string _Material = dt_excel.Rows[i][2].ToString();
                        string _Priority = dt_excel.Rows[i][3].ToString();


                        if (!string.IsNullOrEmpty(_Material))
                        {
                            LstSAPUploadList.Add(new SAP_SOITEM_Analysis
                            {
                                Item = _Item,
                                LotNum = txtLotNumber.Text,
                                Priority = _Priority,
                                Material = _Material,
                                Order = _Order,
                                Creator = txtUserName.Text
                            });
                        }
                    }
                }
                this.gridControl1.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();
                if (MessageBox.Show("确定要进行上传数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {


                    if (LstSAPUploadList.Count > 0)
                    {
                        StringBuilder sbm = new StringBuilder();
                        using (Session session = new Session(clsGetInstanceDataLayer.getInstance().getIDataLayer()))
                        {

                            session.ExplicitCommitTransaction();
                            foreach (SAP_SOITEM_Analysis item in LstSAPUploadList)
                            {
                                StringBuilder sbSql = new StringBuilder();
                                sbSql.Append("EXEC sp_Upload_SAP_SOITEM_Analysis ");
                                sbSql.AppendFormat("@SOOrder ='{0}', ", item.Order);
                                sbSql.AppendFormat("@SOItem ='{0}', ", item.Item);
                                sbSql.AppendFormat("@Material ='{0}', ", item.Material);
                                sbSql.AppendFormat("@Priority ='{0}', ", item.Priority);
                                sbSql.AppendFormat("@LotNumber ='{0}', ", item.LotNum);
                                sbSql.AppendFormat("@Creator ='{0}'", txtUserName.Text);
                                LstSQL.Add(sbSql.ToString());

                            }
                            DbHelperSQL.ExecuteSqlTran(LstSQL);
                            MessageBox.Show("上传完毕，请核实!");
                        }
                    }
                }

                this.GetDataFromSystem();
            }
        }

 

        private void repositoryItemSpinEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }

  
 
  

        /// <summary>
        /// 获得模板SN
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public string GetSNByType(string typeName)
        {
            StringBuilder sbSql_sn = new StringBuilder();
            sbSql_sn.Append("SELECT top 1   z.SN  FROM SAP_Template_Version z ");
            sbSql_sn.AppendFormat("WHERE z.TypeName='{0}' ", typeName);
            return DbHelperSQL.Query(sbSql_sn.ToString()).Tables[0].Rows[0]["SN"].ToString();
        }

        private void InitWCGLookupList()
        {

            StringBuilder sbSql = new StringBuilder();
            sbSql.Append("SELECT sph.[GROUP], sph.Main_Group, sph.Subgroup, sph.Prod_Hierarchy, ");
            sbSql.Append("       sph.Prod_Hierarchy_Code ");
            sbSql.Append("  FROM SAP_ProductHierarchy sph ");
            sbSql.Append("ORDER BY  sph.Prod_Hierarchy_Code ");

            DataSet dstemp = DbHelperSQL.Query(sbSql.ToString());

            if (dstemp != null && dstemp.Tables.Count > 0)
            {


                this.repositoryItemLookUpEdit_PrdHrchy.DataSource = dstemp.Tables[0];
                this.repositoryItemLookUpEdit_PrdHrchy.DisplayMember = "Prod_Hierarchy";
                this.repositoryItemLookUpEdit_PrdHrchy.ValueMember = "Prod_Hierarchy_Code";


            }

        }

 

  

        private void 导入ViewResultToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
          
        }

 
      

  

        private void btn_TableToList_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            List<string> Lst_Component = new List<string>();


            if ((this.gdc_MpsMain.DataSource as System.Data.DataTable) != null)
            {
                foreach (DataRow dr in (this.gdc_MpsMain.DataSource as System.Data.DataTable).Rows)
                {
                    string s = dr["Component_number"].ToString().Trim();
                    if (!Lst_Component.Exists(p => p == s))
                    {
                        Lst_Component.Add(s);
                        sb.AppendFormat("{0}{1}", dr["Component_number"].ToString(), System.Environment.NewLine);
                    }
                }
            }
            rch_MaterialList.Text = "";
            rch_MaterialList.AppendText(sb.ToString());
            this.AppendMessage(string.Format("物料数量【{0}】", Lst_Component.Count));
           
        }

        private void rch_MaterialList_DoubleClick(object sender, EventArgs e)
        {
            rch_MaterialList.SelectAll();
        }

        private void AppendMessage(string msg)
        {
            this.rch_Message.AppendText(msg + System.Environment.NewLine);
        }

        private void rch_Message_DoubleClick(object sender, EventArgs e)
        {
            rch_Message.SelectAll();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            CFunctionUtility.ExportToExcel(this.gridView1);
        }

        private void txtUpload_GY_EditValueChanged(object sender, EventArgs e)
        {

        }

    }

    public class SAP_SOITEM_Analysis
    {

        public string Order { set; get; }
        public string Item { set; get; }
        public string Material { set; get; }
        public string Priority { set; get; }
        public string Creator { get; set; }
        public string LotNum { get; set; }

    }

 

}